import request from '/@/utils/request';
import {
	auth
} from '/@/utils/authFunction';
import {
	getEnumSelectorList,
	enumCodeToName
} from "/@/utils/enumHelper";
import {
	codeToName,
	getConstType
} from "/@/utils/constHelper";
export default (app, option = {}) => {
	// let optionObj = import.meta.glob(`../option/**/**`)[`../option/${option.name}.js`]  
	let apiObj = import.meta.glob(`../api/**/**`)[`../api/${option.name}.ts`]
	let mixins = {
		data() {
			return {
				key: Math.random(),
				data: [],
				form: {},
				search: {},
				params: {},
				option: {},
				api: {},
				loading: false,
				page: {},
				selection: [], //勾选框
				timer: null,
			}
		},
		watch: {

		},
		created() {
			this.getCurrentOption();
			apiObj().then(mode => {
				this.api = mode
				this.handleQuery()
			})
		},
		computed: {
			bindVal() {
				return {
					ref: 'crud',
					key: this.key,
					option: this.option,
					data: this.data,
					tableLoading: this.loading
				}
			},
			onEvent() {
				return {
					'size-change': this.sizeChange,
					'current-change': this.currentChange,
					'row-save': this.rowAdd,
					'row-del': this.rowDel,
					'row-update': this.rowUpdate,
					'refresh-change': this.refreshChange,
					'search-reset': this.searchChange,
					'search-change': this.searchChange,
					'expand-change': this.expandChanges,
					'selection-change': this.selectionChange,
					'sort-change': this.sortChange
				}
			},
			rowKey() {
				return option.rowKey || 'id'
			}
		},
		methods: {
		//获取当前页面的配置
		getCurrentOption() {
			request({
				url: `/api/Common/optionConfig`,
				method: 'post',
				data: option.path
			}).then(res => {
				// this.option = mode.default(this)
				this.option = res.data.result;
				if(this.option==null)
				return;
				this.key = Math.random();
				if (this.option.selectable != null) {
					this.option.selectable = eval(this.option.selectable);
				}
				if(this.option.column!=null){
				this.option.column.forEach(r => {
					r.showFileList = true;
					if (r.dicUrl != undefined && r.dicUrl != null) {
						r.dicUrl = `${request.tempBaseURL}${r.dicUrl}`;
					}
					if (r.action != undefined && r.action != null) {
						r.action = `${request.tempBaseURL}${r.action}`;
					}
					if (r.dicFormatter != null) {
						r.dicFormatter = r.dicFormatter.replace(/"/g, '').replace(/\\/g, '');
						r.dicFormatter = eval(r.dicFormatter);
					}
					if (r.control != undefined && r.control != null) {
						r.control = eval(r.control);
					}
					if (r.fixed_ != null) {
						r.fixed = r.fixed_;
					}
				})
				
				this.$nextTick((x) => {
					this.data.forEach(obj => {
						//遍历对象，key是对象的id名称  {id:1,name:'zz',age:12}
						Object.keys(obj).forEach((key) => {
							let needEdit = this.option.column.find(r => r
								.prop == key && r.cell == 1);
							if (needEdit) {
								obj['$cellEdit'] = true;
							}
						});
					})
				})
				
				}
			})
		},
			getPermission(key) {
				let authName = `${this.option.configCode}:${key}`;
				let hasAuth = false;
				switch (key) {
					case 'delBtn':
						authName = `${this.option.configCode}:delete`;
						break;
					case 'editBtn':
						authName = `${this.option.configCode}:edit`;
						break;
					case 'addBtn':
						authName = `${this.option.configCode}:add`;
						break;
					case 'viewBtn':
						authName = `${this.option.configCode}:detail`;
						break;
					case 'cellBtn':
						break;
					case 'addRowBtn':
						break;
					case 'excelBtn':
						authName = `${this.option.configCode}:export`;
						break;
					case 'printBtn':
						return false;
						break;
					case 'filterBtn':
						return true;
						break;
					case 'columnBtn':
						return true;
						break;
					case 'refreshBtn':
						return true;
						break;
					case 'menu':
						return true;
						break;
					default:
						break;
				}
				return auth(authName);
			},
			getCustomPermission(key) {
				return auth(key);
			},
			sortChange(sortModel) {
				// console.log(val);
				// order:"descending"
				// prop:"check_Remind"
			},
			handleQuery(filters) {
				const callback = () => {
					this.timer = new Date().getTime();
					this.loading = true
					let pageParams = {}
					pageParams[option.pageNumber || 'pageNumber'] = this.page.currentPage
					pageParams[option.pageSize || 'pageSize'] = this.page.pageSize
					const query_data = Object.assign(pageParams, this.params)
					if (filters != undefined && filters.length > 0) {
						query_data.filters = filters;
					}
					this.data = []

					if (this.api[option.list] === undefined) {
						return;
					}
					this.api[option.list](query_data).then(res => {
						this.loading = false
						const responseResult = res.data.result;

						this.page.total = responseResult.total;
						const result = responseResult.items;

						this.data = result;
						if (this.listAfter) {
							this.listAfter(this.data)
						}
					})
				}
				if (this.listBefore) {
					this.listBefore()
				}
				callback()
			},
			//handleQuery(ccc){
			//	console.log(ccc);
			//},
			rowAdd(row, done, loading) {
				const callback = () => {
					delete this.form.params
					this.api[option.add || 'add'](this.form).then((data) => {
						this.handleQuery()
						if (this.addAfter) {
							this.addAfter(data)
						} else {
							// this.$message.success('新增成功')
						}
						done()
					}).catch(() => {
						loading()
					})
				}
				if (this.addBefore) {
					this.addBefore()
				}
				callback()
			},
			rowCustomSave(row) {
				const callback = () => {
					delete this.form.params
					this.api[option.save || 'save'](row).then((data) => {
						this.handleQuery()
						if (this.addAfter) {
							this.addAfter(data)
						}
					})
				}
				if (this.addBefore) {
					this.addBefore()
					callback()
				}else {
					this.$confirm(`是否保存数据?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						callback()
					})
				}
			},
			rowUpdate(row, index, done, loading) {
				const callback = () => {
					delete this.form.params
					// row[this.rowKey],
					this.api[option.update || 'update'](this.form, index).then((data) => {
						this.handleQuery()
						if (this.updateAfter) {
							this.updateAfter(data)
						} else {
							// this.$message.success('更新成功')
						}
						done()
					}).catch(() => {
						loading()
					})
				}
				if (this.updateBefore) {
					this.updateBefore()
				}
				callback()
			},
			rowDel(row, index) {
				const callback = () => {
					// row[this.rowKey], 
					this.api[option.del || 'del'](row).then((data) => {
						this.handleQuery()
						if (this.delAfter) {
							this.delAfter(data, row, index)
						} else {
							// this.$message.success('删除成功')
						}
					})
				}
				if (this.delBefore) {
					this.delBefore()
					callback()
				} else {
					this.$confirm(`此操作将永久删除序号【${index+1}】的数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						callback()
					})
				}
			},
			searchChange(params, done) {
				if (done) done()
				this.params = params
				this.page.currentPage = 1;
				//Avue会把datetime类型的字段改成日期数组集合，而后端此类型的字段为 DateTime ,则会导致报错
				//所以：在前端拼接 日期集合传给后端即可
				var dateTimeColumnList = this.option.column.filter(r =>
					(r.type == 'datetime' && r.searchRange == true) ||
					(r.type == 'select' && r.multiple == true)
				);
				dateTimeColumnList.forEach(r => {
					if (r.type == 'datetime') {
						var newPropName = `${r.prop}Range`;
						this.params[newPropName] = this.params[r.prop];
						this.params[r.prop] = null;
					}
					
					if (r.type == 'select') {
					    var newPropName = `${r.prop}List`;
						this.params[newPropName] = this.params[r.prop]?.split(',');
						this.params[r.prop] = null;
					}
				});
				this.handleQuery()
			},
			refreshChange() {
				this.handleQuery()
			},
			sizeChange(val) {
				this.page.currentPage = 1
				this.page.pageSize = val
				this.handleQuery()
			},
			currentChange(val) {
				this.page.currentPage = val
				this.handleQuery()
			},
			//展开
			expandChanges(row, expendList) {
				this.timer = new Date().getTime();
				if (expendList.length) {
					this.option.expandRowKeys = []
					if (row) {
						this.option.expandRowKeys.push(row.id)
					}
				} else {
					this.option.expandRowKeys = []
				}
			},
			selectionChange(val) {
				//单选
				if (this.option.tableMultiple == false) {
					if (val.length > 1) {
						let del_row = val.shift();
						this.$refs.crud.toggleRowSelection(del_row, false);
					}
					this.selection = this.$refs.crud.tableSelect;
				} else { //多选
					this.selection = val;
				}
				if (this.selectAfter)
					this.selectAfter(this.selection);
			},
			getEnumCodeToName(enumValue, enumTypeName) {
				return enumCodeToName(enumValue, enumTypeName);
			},
			getConstToName(constValue, constTypeName) {
				return codeToName(constValue, constTypeName);
			},
			//行拖拽
			sortableChange(oldindex, newindex, row, list) {
				// this.$message.success(oldindex + ',' + newindex)
				// console.log(this.data);
				console.log('拖拽成功！' + oldindex, newindex)
			},
			//列字段点击查询数据库排序
			sortChange(val) {
				this.params.order = val.order;
				this.params.field = val.prop;
				this.handleQuery();
			},
			//自定义的打印功能
			customHandlePrint() {
				this.$Print('#table');
			},
			//多条件过滤
			filterChange(filters) {
				request({
					url: `/api/common/optionFilter/${this.option.configCode}`,
					method: 'post',
					data: filters
				}).then(res => {
					console.log(res);
				})

			},
		}
	}
	app.mixins = app.mixins || []
	app.mixins.push(mixins)
	return app
}